package com.xiaoqi.ClentCount;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author Rookie Coder
 * @Description 在线客户端统计
 * @Date
 **/
public class MyRequestLister implements ServletRequestListener {
    @Override
    public void requestDestroyed(ServletRequestEvent servletRequestEvent) {

    }

    /*
     * @Author liu-miss
     * @Description  将当前session对象存放到List中
     * @Date 17:14 2021/5/3
     * @Param [sre]
     * @return void
     **/
    @Override
    public void requestInitialized(ServletRequestEvent sre) {

        // 获取当前request
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
        // 获取当前ip
        String clientip = request.getRemoteAddr();
        // 获取当前session对象
        HttpSession currentsession = request.getSession();

        // 获取全局域
        ServletContext sc = sre.getServletContext();
        // 从全局域中获取map
        Map<String, List<HttpSession>> map = (Map<String, List<HttpSession>>) sc.getAttribute("map");
        // 从map中获取由当前ip所发出的所有session组成的List
        List<HttpSession> httpSessions = map.get(clientip);
        //判断当前的List是否为null，若为null，则创建List，若不是，就直接将当前Session放入这个List
        if (httpSessions == null) {
            httpSessions = new ArrayList<>();
        } else {
            //遍历list，若list存在当前session对象，则不用操作List
            for (HttpSession session : httpSessions) {
                if (session == currentsession) {
                    return;
                }
            }
            // 将当前session放入List中
            httpSessions.add(currentsession);
            // 将变化后的List写会Map中
            map.put(clientip, httpSessions);
            // 将变化后的Map写回到全局域中
            sc.setAttribute("map", map);

            // 将当前ip放入session域中
            currentsession.setAttribute("celientIp", clientip);
        }


    }
}
